//
//  ViewController.m
//  pickerView的第三种方法 9-10
//
//  Created by 伍银荣 on 2017/9/10.
//  Copyright © 2017年 WYR. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
{
    //创建pickerView属性
    UIPickerView *pv;
    //创建存放数组的字典
    NSDictionary *dict;
    //创建一个选择时的对象
    NSString *selectKey;
    //存放键名
    NSArray *keys;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    pv = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    
    pv.dataSource = self;
    pv.delegate = self;
    
    [self.view addSubview:pv];
    //设置数据
    dict = @{@"湖南":@[@"衡阳",@"株洲",@"长沙",@"岳阳",@"益阳",@"张家界",@"常德",@"郴州"],@"广东":@[@"深圳",@"潮州",@"广州",@"东莞",@"佛山",@"珠海"],@"福建":@[@"厦门",@"福州",@"泉州",@"三明市",@"莆田市",@"漳州市"]};
    //拿到所有的键名
    keys =  [dict allKeys];
    //默认选择第1列
    selectKey = [keys objectAtIndex:0];
    NSLog(@"%@",dict);
}

//数据源方法
//返回多少列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

//返回多少行
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return keys.count;
    }else{
        return [[dict objectForKey:selectKey] count];
    }
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return [keys objectAtIndex:row];
    }else{
        return [[dict objectForKey:selectKey] objectAtIndex:row];
    }
}


-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        selectKey = [keys objectAtIndex:row];
        [pickerView reloadComponent:1];
    }
}




@end
